package com.example.travelsn.navigate;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.travelsn.R;
import com.example.travelsn.cate.CateHome;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class NavigationDetail extends AppCompatActivity implements View.OnClickListener, OnGetSuggestionResultListener {
    private Button walkPlan;
    private ImageView bMyLocation;
    private AutoCompleteTextView startP,terminalP;
    private ListView beginSuglist,endSuglist;
    private SuggestionSearch mSuggestionSearch = null;
    public SimpleAdapter simpleAdapter,instantAdapter=null;
    //判断当前编辑文本框是起点还是终点
    private int editType = 0;
    private String nCity,nLocation;
    //我的位置监听
    private Boolean isMyLocation = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.navigation_detail);
        //获取当前位置信息（城市和详细地址）
        SharedPreferences sharedPreferences = getSharedPreferences("navigationdetail", Activity.MODE_PRIVATE);
        nCity =  sharedPreferences.getString("detailcity","杭州");
        nLocation =  sharedPreferences.getString("location","not logged");
        initView();
        PoiSugSearch();
        button();
        request();
        //ListView监听
        endSuglist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,String> map=(HashMap<String,String>)endSuglist.getItemAtPosition(position);
                String text =  endSuglist.getAdapter().getItem(position).toString();
                // 将点击的item里面的字弹出来
                Toast.makeText(NavigationDetail.this, text, Toast.LENGTH_SHORT).show();
                if(editType == 1){
                        startP.setText(map.get("key"));
                    }else terminalP.setText(map.get("key"));
            }
        });
        //我的位置按钮监听
        bMyLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startP.setText("我的位置");
                isMyLocation = true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.b_walkplan:
                if(startP.getText().toString().equals("") || terminalP.getText().toString().equals("")){
                    Toast.makeText(NavigationDetail.this, "请输入完整信息",
                            Toast.LENGTH_SHORT).show();
                }
                else{
                    Intent intent = new Intent();
                    intent.putExtra("terminal", terminalP.getText().toString());
                    //                    //判断是否选择我的位置
                    if(isMyLocation){
                        intent.putExtra("isthere",1);
                        isMyLocation = false;
                    }
                    else {
                        intent.putExtra("start",startP.getText().toString());
                        intent.putExtra("isthere",0);
                    }
                    setResult(01, intent);
                    finish();
                }
                break;
            default:

        }
    }
    //按钮响应
    private void button() {
        //按钮
        walkPlan = (Button) findViewById(R.id.b_walkplan);
        bMyLocation = (ImageView)findViewById(R.id.iv_myloc);
        //按钮处理
        walkPlan.setOnClickListener(this);
        bMyLocation.setOnClickListener(this);
    }
    private void initView() {
        this.startP = (AutoCompleteTextView)findViewById(R.id.et_startpoint);
        this.terminalP = (AutoCompleteTextView)findViewById(R.id.et_terminalpoint);
        this.beginSuglist = (ListView)findViewById(R.id.b_suglist);
        this.endSuglist = (ListView)findViewById(R.id.e_suglist);
        startP.setThreshold(1);
        terminalP.setThreshold(1);
    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
            return;
        }
        List<HashMap<String, String>> suggest = new ArrayList<>();
        for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            if (info.getKey() != null && info.getDistrict() != null && info.getCity() != null) {
                HashMap<String, String> map = new HashMap<>();
                map.put("key",info.getKey());
                map.put("city",info.getCity());
                map.put("dis",info.getDistrict());
                suggest.add(map);
            }
        }
        simpleAdapter = new SimpleAdapter(getApplicationContext(),
                suggest,
                R.layout.layout_map,
                new String[]{"key","city","dis"},
                new int[]{R.id.sug_key, R.id.sug_city, R.id.sug_dis});
        endSuglist.setAdapter(simpleAdapter);
        beginSuglist.setAdapter(simpleAdapter);
        simpleAdapter.notifyDataSetChanged();
    }
    //开始POI搜索，此下位POI搜索方法
    //POI
    private void PoiSugSearch(){
        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
    }
    private void request(){
        // 当输入关键字变化时，动态更新建议列表
        startP.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {
                endSuglist.setAdapter(instantAdapter);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                editType = 1;
                if (cs.length() <= 0) {
                    return;
                }
                // 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                        .keyword(cs.toString()) // 关键字
                        .city(nCity)); // 城市
            }
        });
        terminalP.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                simpleAdapter=null;
                System.out.println("beforeTextChanged这个在运行");
                endSuglist.setAdapter(simpleAdapter);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                editType = 2;
                if (s.length() <= 0) {
                    return;
                }
                // 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                        .keyword(s.toString()) // 关键字
                        .city(nCity)); // 城市
            }

            @Override
            public void afterTextChanged(Editable s) {
                endSuglist.setAdapter(instantAdapter);
            }
        });
    }


}
